package icasue.net.socket.utils;

import com.alibaba.fastjson.JSON;
import icasue.net.base.annotations.NotNull;
import icasue.net.base.annotations.Nullable;
import icasue.net.protocol.carfun.common.Const;
import icasue.net.socket.exception.ProtocolException;
import icasue.net.socket.exception.ProtocolParserException;
import icasue.net.socket.exception.ProtocolUnSupportException;

import java.util.Map;

/**
 * @Author: Qiao Hang
 * @CreateDate: 2021/3/19 下午2:45
 * @UpdateDate:
 * @Description:
 */
public class ProtocolUtil {

    public static JSON parseRequestData(@NotNull Map<String,String> headers, @Nullable String data) throws ProtocolException {
        JSON json = null;
        if(data != null){
            switch (headers.get(Const.DataType)){
                case Const.DataType_JSON:
                    if(JSON.isValidObject(data)){
                        json = JSON.parseObject(data);
                    }else {
                        /*抛出协议解析数据类型不匹配异常*/
                        throw new ProtocolParserException("Protocol parser DataType dis matched.");
                    }
                    break;
                case Const.DataType_JSONAry:
                    if(JSON.isValidArray(data)){
                        json = JSON.parseArray(data);
                    }else {
                        /*抛出协议解析据类型不匹配异常*/
                        throw new ProtocolParserException("Protocol parser DataType dis matched.");
                    }
                    break;
                default:
                    /*抛出协议解析数据类型不支持异常*/
                    throw new ProtocolUnSupportException("Protocol DataType UnSupported.");
            }
        }
        return json;
    }


}
